﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Editing;
using ExORMDesginer.Services;
using ExORMDesginer.Models;
using ExORMDesginer.Plugin;

namespace ExORMDesginer.UserControls.CCodeEditer
{

    public abstract class CompletionManager
    {
        public CompletionWindow completionWindow;

        public IList<ICompletionData> CompletionData
        {
            set;
            get;
        }

        public  virtual bool ShowCompletion(TextArea textArea, params object[] args)
        {
            return false;
        }
    }



    public class DataBaseCompletionManager : CompletionManager
    {
        public DataBaseCompletionManager():base()
        {

        }


        public override bool ShowCompletion(TextArea textArea, params object[] args)
        {
            string tableName =string.Empty;
            if(args !=null && args.Length > 0)
              tableName = args[0].ToString();
            completionWindow = new CompletionWindow(textArea);
            IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
            var isn = ServiceManager.GetService<DatabaseMetaService>();
            if (isn == null) return false;
            var dict = isn.GetContext() as Dictionary<string, DbEntity>;
            //field names
            if (!string.IsNullOrEmpty(tableName))
            {
                DbEntity table;
                if (dict.TryGetValue(tableName, out table))
                {
                    var cd = completionWindow.CompletionList.CompletionData;
                    foreach (var field in table.Propertys)
                    {
                        cd.Add(new FieldsCompletionData(field));
                    }
                }
                else
                    return false;
            }//table names
            else
            {
                var cd = completionWindow.CompletionList.CompletionData;
                foreach (var table in dict.Values)
                {
                    cd.Add(new TableCompletionData(table));
                }
            }

            completionWindow.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            completionWindow.Show();
            completionWindow.Closed += delegate
            {
                completionWindow = null;
            };
            return true;
        }




    }
}
